package com.haha.gulimallsearch.service.impl;

import cn.hutool.json.JSONUtil;
import com.haha.common.to.es.SkuEsModel;
import com.haha.gulimallsearch.config.ElasticSearchConfig;
import com.haha.gulimallsearch.constant.EsConstant;
import com.haha.gulimallsearch.service.ProductSaveService;
import lombok.extern.log4j.Log4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    RestHighLevelClient restHighLevelClient;
    /**
     *
     * 商品上架
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest();
            String jsonStr = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.index(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(jsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(bulk.toString());
        if(bulk.hasFailures()){
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
                StringBuffer aa = new StringBuffer("商品上架错误：");
            for (String skuId : collect) {
             aa.append(skuId+",");
            }

        }
        return bulk.hasFailures();
    }
}
